import Vue from 'vue';
import VueRouter from 'vue-router';
import store from '@/store/index';

// 首页
import home from "@/router/home";
// 系统管理
import system from "@/router/system";
// 其他
import others from "@/router/others";

//订单管理
import order from './order';
//优惠券管理
import coupon from './coupon';
//财务管理
import myWallet from './myWallet';

//停车场管理
import parking from '@/router/parking';
//车辆管理
import cars from '@/router/cars';
//商城管理
import mall from '@/router/mall';
//用户管理
import user from '@/router/user';
// 故障处置
import fault from '@/router/fault';
//广告管理
import adv from './adv';
import plateform  from './plateform';
Vue.use(VueRouter);

const routes = [
  ...home,
  ...system,
  ...others,
  ...order,
  ...coupon,
  ...myWallet,
  ...parking,
  ...mall,
  ...cars,
  ...fault,
  ...adv,
  ...user,
  ...plateform
];

const router = new VueRouter({
  routes
});

// beforeEach是router的钩子函数，在进入路由前执行
router.beforeEach((to, from, next) => {
  // 判断导航路由是否有值
  if(store.state.menu.length === 0){
    if(window.storage.getItem(window.storage.key.token)){
      // 没有值，开始加载导航
      store.dispatch("initMenu").then(()=>{
        // 判断进入的页面是否需要身份验证
        if(to.meta.requiresAuth){
          if(getAuth(to.path, store.state.menu)){
            // 有权限
            next();
          }else{
            // 没有权限
            next({path: "/401"});
          }
        }else{
          // 不需要验证直接进入
          next();
        }
      });
    }else{
      if(to.name !== "Login"){
        // 未登录
        next({name: "Login", query: {rewrite: location.href}});
      }else{
        next();
      }
    }
  }else{
    // 判断进入的页面是否需要身份验证
    if(to.meta.requiresAuth){
      // 权限路由有值
      if(getAuth(to.path, store.state.menu)){
        // 有权限
        next();
      }else{
        // 没有权限
        next({path: "/401"});
      }
    }else{
      // 不需要验证直接进入
      next();
    }
  }
});

/**
 * 身份验证
 */
function getAuth(path, list){
  let result = window.utils.util.findLeafPathInTree(list, path, {
    value: "menuId",
    children: "children",
    compare: "url"
  });
  return result && result.length > 0;
}



export default router;
